package com.cy.store11.service.impl;

import com.cy.store11.entity.User;
import com.cy.store11.mapper.UserMapper;
import com.cy.store11.service.IUserService;
import com.cy.store11.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

/**用户模块业务层的实现类*/
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void reg(User user) {
        //通过user参数来获取传递过来的username
        String username = user.getUsername();
        //调用findByUsername(username)判断用户是否被注册
       User result =  userMapper.findByUsername(username);
       //判断结果集是否不为null，则抛出用户名被占用的异常
        if(result !=null){
            throw new UsernameDuplicatedException("用户名被占用");
        }
        String oldPassword = user.getPassword();
        String salt = UUID.randomUUID().toString().toUpperCase();
        user.setSalt(salt);
        //最终密码
        String md5Password = getMD5Password(oldPassword,salt);
        user.setPassword(md5Password);
        //补全数据：is_delete设置为0
        user.setIsDelete(0);
        //补全数据：4个日志字段信息
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date = new Date();
        user.setModifiedTime(date);
        user.setCreatedTime(date);

        //执行注册业务功能的实现(rows==1)
        Integer rows = userMapper.insert(user);
        if(rows != 1){
            throw new InsertException("在用户注册过程中产生了未知的异常");
        }
    }

    @Override
    public User login(String username, String password) {
        //根据用户名称来查询用户的数据是否存在，如果不存在则抛出异常
       User result =  userMapper.findByUsername(username);
       if(result == null)
       {
           throw new UsernameNotFoundException("用户数据不存在");
       }
       //检测用户的密码是否匹配
        String salt = result.getSalt();
        String result_password = result.getPassword();
        String inputMd5Password = getMD5Password(password,salt);

        if(!inputMd5Password.equals(result_password  ))
        {
            throw new PasswordNotMatchException("密码错误");
        }
        //判断is_delete字段的值是否为1被标记为删除
        if(result.getIsDelete() == 1)
        {
            throw new UsernameNotFoundException("用户数据不存在");
        }
        //调用mapper层的findByUsername
        User user = userMapper.findByUsername(username);
        //将当前的用户数据返回
        return user;
    }

    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword) {
        User result = userMapper.findByUid(uid);
        if(result == null || result.getIsDelete() ==1){
            throw new UsernameNotFoundException("用户数据不存在");
        }
        //检测原来密码是否正确
        String salt = result.getSalt();
        String result_password = result.getPassword();
        String inputMd5Password = getMD5Password(oldPassword,salt);
        if(!result_password.equals(inputMd5Password)){
            throw new PasswordNotMatchException("原密码错误");
        }
        //将新的密码设置到数据库中，将新的密码进行加密
        String inputMd5newPassword = getMD5Password(newPassword,salt);
        Integer rows = userMapper.updatePasswordByUid(result.getUid(), inputMd5newPassword,username,new Date());
        if(rows !=1){
            throw new UpdateException("更新数据出现异常");
        }
    }

    /**
     *
     * @param uid 用户id
     * @return
     */

    @Override
    public User getByUid(Integer uid) {
        User result = userMapper.findByUid(uid);
        if(result == null || result.getIsDelete() ==1 ){
            throw new UsernameNotFoundException("用户数据不存在");
        }
        User user = new User();
        user.setUsername(result.getUsername());
        user.setPhone(result.getPhone());
        user.setAvatar(result.getAvatar());
        user.setEmail(result.getEmail());
        user.setGender(result.getGender());
        return user;
    }

    @Override
    public void changeInfo(Integer uid, String username, User user) {
        User result = userMapper.findByUid(uid);
        if(result == null || result.getIsDelete() ==1){
            throw new UsernameNotFoundException("用户数据不存在");
        }
        user.setUid(uid);
        user.setModifiedUser(username);
        user.setModifiedTime(new Date());
        Integer rows = userMapper.updateInfoByUid(user);
        if(rows !=1 )
        {
            throw new UpdateException("更新数据时出现未知错误");
        }

    }

    @Override
    public void changeAvatar(Integer uid, String avatar, String username) {
        User result = userMapper.findByUid(uid);
        if(result == null || result.getIsDelete() ==1){
            throw new UsernameNotFoundException("用户数据不存在");
        }
        Integer rows = userMapper.updateAvatarByUid(result.getUid(), avatar,username,new Date());
        if(rows !=1){
            throw new UpdateException("更新头像出现异常");
        }
    }


    /**定义一个md5算法的加密处理*/
    private String getMD5Password(String password, String salt)
    {
        for(int i=0;i<3;i++){
         password  =  DigestUtils.md5DigestAsHex((salt+password+salt).getBytes());
        }
        return password;
    }
}
